<?php

class merchantActions extends sfActions {

  public function executeAddMerchant(sfWebRequest $request) {
    if ($request->getParameter('did')) {
      $merchant = MERCHANTTable::getInstance()->find($request->getParameter('did'));
      $this->forward404Unless($merchant instanceof MERCHANT);
      $merchant->setStatus(Constants::STATUS_INACTIVE);
      $merchant->save();
      $this->redirect('@merchant_add');
    }

    $this->form = new MerchantForm();

    $errorCollector = array();

    if ($request->hasParameter('id')) {
      $merchant = MERCHANTTable::getInstance()->find($request->getParameter('id'));
      $this->forward404Unless($merchant instanceof MERCHANT);
      $this->isEdit = true;
      $this->form->populateData($merchant);
    } else {
      $merchant = new MERCHANT();
    }

    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(MerchantForm::FORM_NAME);
        $this->form->bind($formData);

        if ($this->form->isValid()) {

          $merchant->setName($formData[MerchantForm::FIELD_NAME]);
          $merchant->setAbn(($formData[MerchantForm::FIELD_ABN]) ? $formData[MerchantForm::FIELD_ABN]: null);
          //$merchant->setBankDetails(($formData[MerchantForm::FIELD_BANK_DETAILS]) ? $formData[MerchantForm::FIELD_BANK_DETAILS]: null);
          $merchant->setAccountName(($formData[MerchantForm::FIELD_ACCOUNT_NAME]) ? $formData[MerchantForm::FIELD_ACCOUNT_NAME]: null);
          $merchant->setBsb(($formData[MerchantForm::FIELD_BSB]) ? $formData[MerchantForm::FIELD_BSB]: null);
          $merchant->setAccountNumber(($formData[MerchantForm::FIELD_ACCOUNT_NUM]) ? $formData[MerchantForm::FIELD_ACCOUNT_NUM]: null);
          $merchant->setEmail($formData[MerchantForm::FIELD_EMAIL]);
          $merchant->setPhone(($formData[MerchantForm::FIELD_PHONE]) ? $formData[MerchantForm::FIELD_PHONE]: null);
          $merchant->setMobile(($formData[MerchantForm::FIELD_MOBILE]) ? $formData[MerchantForm::FIELD_MOBILE]: null);
          $merchant->setFax(($formData[MerchantForm::FIELD_FAX]) ? $formData[MerchantForm::FIELD_FAX] : null);
          $merchant->setCommission(($formData[MerchantForm::FIELD_COMMISSION]) ? $formData[MerchantForm::FIELD_COMMISSION] : null);
          $merchant->setBookingFee(($formData[MerchantForm::FIELD_BOOKING_FEE]) ? $formData[MerchantForm::FIELD_BOOKING_FEE] : null);
          $merchant->setStatus($formData[MerchantForm::FIELD_STATUS]);
          $merchant->save();

          $this->redirect('@merchant_add?success=1');
        }
      }
    } catch (Exception $e) {
      $errorCollector[] = LangUtil::getText('error_save_failed');
    }

    $this->errorCollector = $errorCollector;

    try {
      $sortBy = $request->hasParameter(sfConfig::get('app_sort_parameter_name')) ? $request->getParameter(sfConfig::get('app_sort_parameter_name')) : MerchantForm::SORT_NAME;
      $pager = new sfDoctrinePager('Merchant', sfConfig::get('app_list_records_per_page'));
      $pager->setQuery(Doctrine_Query::create()->from('MERCHANT m')->orderBy('m.' . $sortBy));
      $pager->setPage($request->getParameter(sfConfig::get('app_paginator_parameter_name'), 1));
      $pager->init();
      $this->pager = $pager;
    } catch (Exception $e) {
      $this->forward404();
    }
  }

  public function executeAddUser(sfWebRequest $request) {
    $this->merchant = MERCHANTTable::getInstance()->find($request->getParameter('mid', $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID)));
    $this->forward404Unless($this->merchant instanceof MERCHANT);
    if ($request->getParameter('mid')) {
      $this->getUser()->setAttribute(Constants::SESSION_MERCHANT_ID, $request->getParameter('mid'));
    }

    $this->form = new MerchantUserForm();

    $errorCollector = array();

    $trans = SystemUtil::beginDoctrineTransaction();

    if ($request->hasParameter('id')) {
      $user = USERTable::getInstance()->find($request->getParameter('id'));
      $this->forward404Unless($user instanceof USER);
      $this->forward404If($this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID) && $user->getMerchantId() != $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
      $this->isEdit = true;
      $this->form->populateData($user);
    } else {
      $user = new USER();
      $this->form->setDefault(MerchantUserForm::FIELD_MERCHANT_ID, $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
    }
    $this->form->setUser($user);

    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(MerchantUserForm::FORM_NAME);
        $this->form->bind($formData);

        if ($this->form->isValid()) {
          $user->setFirstName($formData[MerchantUserForm::FIELD_FIRST_NAME]);
          $user->setLastName($formData[MerchantUserForm::FIELD_LAST_NAME]);
          if (!isset($this->isEdit)) {
            $user->setMerchantId($formData[MerchantUserForm::FIELD_MERCHANT_ID]);
            $user->setUsername($formData[MerchantUserForm::FIELD_EMAIL]);
            $user->setEmail($formData[MerchantUserForm::FIELD_EMAIL]);
            $salt = StringUtil::generateRandomString(20);
            $user->setSalt($salt);
            $tmpPassword = StringUtil::generateRandomString(8);
            $password = StringUtil::hashPassword(trim($tmpPassword), $salt);
            $user->setPassword($password);
            $user->setType(Constants::USER_TYPE_BASIC_ACCOUNT);
          }
          $user->setUserGroupId($formData[MerchantUserForm::FIELD_TYPE]);
          $user->setStatus($formData[MerchantUserForm::FIELD_STATUS]);
          $user->save();

          if (!isset($this->isEdit)) {
            $email = new EMAIL();
            $email->setEmailTo($user->getEmail());
            $email->setSubject('Welcome to Supertain');
            $email->setMessage(array('name' => $user->getFirstName(), 'username' => $user->getUsername(), 'password' => $tmpPassword, 'url' => $this->getController()->genUrl('signin', true)));
            $email->setTemplateFile('merchantUserRegister');
            $email->setContentType(emailTask::CONTENT_TYPE_HTML);
            $email->save();
          }

          SystemUtil::commitDoctrineTransaction($trans);

          $this->redirect('@user_add?success=1');
        }
      }
    } catch (Exception $e) {
      $errorCollector[] = LangUtil::getText('error_save_failed');
      SystemUtil::rollbackDoctrineTransaction($trans);
    }

    $this->errorCollector = $errorCollector;

    try {
      $sortBy = $request->hasParameter(sfConfig::get('app_sort_parameter_name')) ? $request->getParameter(sfConfig::get('app_sort_parameter_name')) : MerchantUserForm::SORT_FIRST_NAME;
      $pager = new sfDoctrinePager('User', sfConfig::get('app_list_records_per_page'));
      $pager->setQuery(Doctrine_Query::create()->from('USER u')->where('u.MERCHANT_ID = ?', $this->merchant->getId())->orderBy('u.' . $sortBy));
      $pager->setPage($request->getParameter(sfConfig::get('app_paginator_parameter_name'), 1));
      $pager->init();
      $this->pager = $pager;
    } catch (Exception $e) {
      $this->forward404();
    }
  }

  public function executeAddCinema(sfWebRequest $request) {
    $this->merchant = MERCHANTTable::getInstance()->find($request->getParameter('mid', $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID)));
    $this->forward404Unless($this->merchant instanceof MERCHANT);
    if ($request->getParameter('mid')) {
      $this->getUser()->setAttribute(Constants::SESSION_MERCHANT_ID, $request->getParameter('mid'));
    }

    $this->form = new CinemaForm();

    $errorCollector = array();

    if ($request->hasParameter('id')) {
      $cinema = CINEMATable::getInstance()->find($request->getParameter('id'));
      $this->forward404Unless($cinema instanceof CINEMA);
      $this->forward404If($this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID) && $cinema->getMerchantId() != $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
      $this->isEdit = true;
      $this->form->populateData($cinema);
    } else {
      $cinema = new CINEMA();
      $this->form->setDefault(CinemaForm::FIELD_MERCHANT_ID, $this->getUser()->getAttribute(Constants::SESSION_MERCHANT_ID));
      $this->form->setDefault(CinemaForm::FIELD_NUM_SCREENS, 1);
    }

    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(CinemaForm::FORM_NAME);
        $formFiles = $request->getFiles(CinemaForm::FORM_NAME);
        $this->form->bind($formData, $formFiles);

        if ($this->form->isValid()) {

          if (!isset($this->isEdit)) {
            $cinema->setMerchantId($formData[CinemaForm::FIELD_MERCHANT_ID]);
          }
          $cinema->setName($formData[CinemaForm::FIELD_NAME]);
          $cinema->setNumScreens($formData[CinemaForm::FIELD_NUM_SCREENS]);
          $cinema->setStateId($formData[CinemaForm::FIELD_STATE_ID]);
          $cinema->setStreetNumber($formData[CinemaForm::FIELD_STREET_NUMBER]);
          $cinema->setStreetName($formData[CinemaForm::FIELD_STREET_NAME]);
          $cinema->setSuburb($formData[CinemaForm::FIELD_SUBURB]);
          $cinema->setPostalCode($formData[CinemaForm::FIELD_POSTAL_CODE]);
          $cinema->setStatus($formData[CinemaForm::FIELD_STATUS]);

          $monviaHttpClient = new MonviaHttpClient();
          $uri = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($cinema->getAddress() . ', Australia') . '&sensor=false';
          $monviaHttpClient->get($uri, array());

          if ($monviaHttpClient->isResponseOk()) {
            $data = $monviaHttpClient->getResponseBody();
            if (isset($data->results[0])) {
              $cinema->setLatitude($data->results[0]->geometry->location->lat);
              $cinema->setLongitude($data->results[0]->geometry->location->lng);
              if (!$cinema->getLatitude() || !$cinema->getLongitude()) {
                throw new Exception('Unable to find the map location. Please make sure Cinema Address is correct.', -1);
              }
              $timezone = DatetimeUtil::getTimeZomeByLocation($cinema->getLongitude(), $cinema->getLatitude());
              $cinema->setTimeZone($timezone);
              $cinema->setUrlGmap('http://maps.google.com/maps?q=' . $cinema->getLatitude() . ',' . $cinema->getLongitude());
            } else {
              throw new Exception('Unable to find the map location. Please make sure Cinema Address is correct.', -1);
            }
          } else {
            throw new Exception('Unable to fetch map location. Please try again in a moment.', -1);
          }

          $cinema->save();
          
          if ($formFiles[CinemaForm::FIELD_LOGO_FILE]['tmp_name']) {
            $fileName = sfConfig::get('sf_upload_dir') . '/' . uniqid() . '.jpg';
            move_uploaded_file($formFiles[CinemaForm::FIELD_LOGO_FILE]['tmp_name'], $fileName);
            $fileName2 = sfConfig::get('sf_upload_dir') . '/logos/' . $cinema->getId() . '.jpg';
            if (file_exists($fileName2)) {
              unlink($fileName2);
            }
            
            ThumbnailGen::resizeImage($fileName, 30, 30, 0, $fileName2, 100);
            unlink($fileName);
          }
          
          $this->redirect('@cinema_add?success=1');
        }
      }
    } catch (Exception $e) {
      if ($e->getCode() === -1) {
        $errorCollector[] = $e->getMessage();
      } else {
        $errorCollector[] = LangUtil::getText('error_save_failed');
      }
    }

    $this->errorCollector = $errorCollector;

    try {
      $sortBy = $request->hasParameter(sfConfig::get('app_sort_parameter_name')) ? $request->getParameter(sfConfig::get('app_sort_parameter_name')) : CinemaForm::SORT_NAME;
      $pager = new sfDoctrinePager('User', sfConfig::get('app_list_records_per_page'));
      $pager->setQuery(Doctrine_Query::create()->from('CINEMA c')->where('c.MERCHANT_ID = ?', $this->merchant->getId())->orderBy('c.' . $sortBy));
      $pager->setPage($request->getParameter(sfConfig::get('app_paginator_parameter_name'), 1));
      $pager->init();
      $this->pager = $pager;
    } catch (Exception $e) {
      $this->forward404();
    }
  }
}